const Service = require('egg').Service;
const _ = require('lodash')

class AppService extends Service {
  //查询客户大列表
  async page({ limit, offset, where }) {
    const { app, app: { model: { Dept, Customer, Contact, Batch, BatchProduct, User } } } = this

    //查询用户
    let child_user_entity =  await this.service.user.getChildUser()

    let child_userid = _.map(child_user_entity, item => item.userid)

    where = {
      $and: [
        [
          {
            $or: [
              {
                created_userid: {
                  $in: child_userid
                }
              },
              { userid: this.ctx.state.user.userid }
            ],
          }
        ],
        where
      ]
    }

    let ret = await Customer.findAndCountAll({
      limit,
      offset,
      include: [
        {
          model: Contact,
          require: false,
        },
        {
          model: Batch,
          required: false,
          include: BatchProduct,
          where: {
            status: '最新'
          }
        },
        {
          attributes: ['name'],
          model: User,
          required: true,
        }
      ],
      where,
      order: [
        ["created_at", "DESC"]
      ]
    })
    return ret
  }

  //获取客户签约信息
  async getCustomerSaleInfo({ customer_id }) {
    const { app, app: { model: { Customer, Contact, Batch, BatchProduct } } } = this
    let ret = await Customer.findAndCountAll({
      include: [
        // {
        //   model: Contact,
        //   require: false,
        // },
        {
          model: Batch,
          required: false,
          include: BatchProduct,
          where: {
            is_new: 1
          }
        }
      ],
      where: {
        id: customer_id
      },
    })
    return ret
  }

}
module.exports = AppService
